// releasePage/pages/publishAnswer/publishAnswer.js
import throttle from '../../../utils/throttle.js';
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        id: '',
        answerId: '',
        content: '', //回答内容
        sceneImageArr: [],
        // 图片描述
        description: [],
        // 当前描述索引
        currentDesIndex: 0,
        // 当前图片索引
        currentPicIndex: 0,
        // 是否展示图片预览
        showPreviewImg: false,
        // 是否展示输入框
        showTextarea: false,
        textareaValue: '',
        // 最大字数限制
        max: 100,
        // 触发照片墙刷新
        refresh: false,
        btnSubmit: true,
        anonymous: false, //评论匿名
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            id: options.id,
            answerId: options.answerId,
        });
        if (options.answerId) {
            this.getAnswerDetail();
        }
    },

    // 添加图片
    addImg(e) {
        const that = this;
        wx.chooseImage({
            count: 9 - that.data.sceneImageArr.length,
            success(res) {
                let imgLen =
                    that.data.sceneImageArr.length + res.tempFilePaths.length;
                if (imgLen > 9) {
                    wx.showModal({
                        content: '最多上传8张图片，请重新上传',
                        showCancel: false,
                    });
                    return;
                } else {
                    wx.showLoading({
                        title: '图片上传中',
                        mask: true,
                    });
                    const imgUploadResults = [];
                    let index = that.data.sceneImageArr.length;
                    for (let i = 0; i < res.tempFilePaths.length; i++) {
                        let imgUploadResult = app
                            .imgUpload(res.tempFilePaths[i])
                            .then((res) => {
                                let num = i + index;
                                that.data.sceneImageArr[num] = res;
                                that.setData({
                                    sceneImageArr: that.data.sceneImageArr,
                                });
                                console.log(that.data.sceneImageArr);
                            });
                        imgUploadResults.push(imgUploadResult);
                    }
                    Promise.all(imgUploadResults).then((values) => {
                        wx.hideLoading();
                    });
                }
            },
        });
    },
    // 删除图片
    deleteImg(e) {
        let index = e.currentTarget.dataset.index;
        console.log(index);
        this.data.sceneImageArr.splice(index, 1);
        // 如果该图片有图片描述也需要删除
        if (this.data.description[index]) {
            this.data.description.splice(index, 1);
        }
        this.setData({
            sceneImageArr: this.data.sceneImageArr,
            description: this.data.description,
        });
    },
    // 预览图片
    previewImgDes(e) {
        let index = e.currentTarget.dataset.index;
        this.setData(
            {
                currentPicIndex: index,
            },
            () => {
                wx.navigateTo({
                    //hideBottom隐藏图片预览的删除按钮
                    url: `../../../pages/checkIn/imgPreview/imgPreview?hideBottom=${true}`,
                });
            }
        );
    },
    // 切换匿名
    toggle() {
        this.setData({
            anonymous: !this.data.anonymous,
        });
    },
    addDescription(e) {
        let index = e.currentTarget.dataset.index;
        this.setData(
            {
                currentDesIndex: index,
            },
            () => {
                this.setData({
                    showTextarea: true,
                    textareaValue:
                        this.data.description[this.data.currentDesIndex] || '',
                });
            }
        );
    },

    onBlur(e) {
        this.setData({
            showTextarea: false,
        });
    },

    onInput(e) {
        this.setData({
            textareaValue: e.detail.value,
        });
        app.numLimitTip(e.detail.value.length, 100);
    },

    submitDescription() {
        this.data.description[
            this.data.currentDesIndex
        ] = this.data.textareaValue;
        this.setData({
            description: this.data.description,
        });
    },
    //回答输入
    contentValue(e) {
        this.setData({
            content: e.detail.value,
        });
    },
    //获取回答详情
    getAnswerDetail() {
        let _that = this;
        wx.request({
            url:
                app.globalData.rootPath +
                `cjMap/getProjectAnswerDetail?authId=${app.globalData.authId}&id=${_that.data.answerId}`,
            method: 'GET',
            header: {
                'content-type': 'application/json',
            },
            success: function (res) {
                console.log(res.data.projectAnswer);
                _that.setData({
                    content: res.data.projectAnswer.content, //回答内容
                    sceneImageArr: res.data.projectAnswer.picurl
                        ? JSON.parse(res.data.projectAnswer.picurl)
                        : [],
                    // 图片描述
                    description: res.data.projectAnswer.picdescription
                        ? JSON.parse(res.data.projectAnswer.picdescription)
                        : [],
                });
            },
        });
    },
    //提交
    submit: throttle(
        function (e) {
            let _that = this;
            if (app.visitorPublish()) return; //游客发布限制
            let photoWalls = [];
            _that.data.sceneImageArr.map((imageUrl, index) => {
                photoWalls.push(_that.data.description[index] || '');
            });
            console.log(_that.data.content);
            if (!_that.data.content || !_that.data.btnSubmit) return;
            // wx.showModal({
            //     title: '确认提交？',
            //     content: '',
            //     success: function (res) {
            //         if (res.confirm) {

            //         } else {
            //             console.log('点击取消回调');
            //         }
            //     },
            // });
            if (!_that.data.answerId) {
                wx.request({
                    url:
                        app.globalData.rootPath +
                        `cjMap/createProjectAnswer?authId=${app.globalData.authId}`,
                    method: 'POST',
                    header: {
                        'content-type': 'application/json',
                    },
                    data: {
                        delflg: '00', //删除标志 00未删除 01已删除 02待审核10草稿
                        pjquestionid: _that.data.id, //项目组id
                        picurls: _that.data.sceneImageArr, //图片
                        content: _that.data.content, //正文
                        picdescriptions: photoWalls,
                        anonymousflg: _that.data.anonymous ? '01' : '00',
                    },
                    success: function (res) {
                        console.log(res);
                        _that.setData({
                            btnSubmit: false,
                        });
                        let pages = getCurrentPages(); //当前页面栈
                        let prevPage = pages[pages.length - 2]; //上一页面
                        let prevPage2 = pages[pages.length - 3];
                        let prevPage3 = pages[pages.length - 4];
                        prevPage.getQuestionDetail();
                        if (typeof prevPage2.refreshQuestion == 'function') {
                            prevPage2.refreshQuestion();
                        }
                        if (
                            prevPage3 &&
                            typeof prevPage3.refreshQuestion == 'function'
                        ) {
                            prevPage3.refreshQuestion();
                        }
                        wx.showToast({
                            title: '提交成功',
                            icon: 'success',
                            duration: 1500,
                        });
                    },
                });
            } else {
                wx.request({
                    url:
                        app.globalData.rootPath +
                        `cjMap/editProjectAnswer?authId=${app.globalData.authId}`,
                    method: 'POST',
                    header: {
                        'content-type': 'application/json',
                    },
                    data: {
                        delflg: '00', //删除标志 00未删除 01已删除 02待审核10草稿
                        pjquestionid: _that.data.id, //项目组id
                        picurls: _that.data.sceneImageArr, //图片
                        content: _that.data.content, //正文
                        picdescriptions: photoWalls,
                        id: _that.data.answerId,
                        anonymousflg: _that.data.anonymous ? '01' : '00',
                    },
                    success: function (res) {
                        console.log(res);
                        _that.setData({
                            btnSubmit: false,
                        });
                        let pages = getCurrentPages(); //当前页面栈
                        let prevPage = pages[pages.length - 2]; //上一页面
                        let prevPage2 = pages[pages.length - 3];
                        let prevPage3 = pages[pages.length - 4];
                        prevPage.getQuestionDetail();
                        if (typeof prevPage2.refreshQuestion == 'function') {
                            prevPage2.refreshQuestion();
                        }
                        if (
                            prevPage3 &&
                            typeof prevPage3.refreshQuestion == 'function'
                        ) {
                            prevPage3.refreshQuestion();
                        }
                        wx.showToast({
                            title: '提交成功',
                            icon: 'success',
                            duration: 1500,
                        });
                    },
                });
            }
            setTimeout(function () {
                wx.navigateBack({
                    delta: 1, // 返回上一级页面。
                });
            }, 2000);
        },
        4000,
        {
            trailing: false,
        }
    ),
});
